package com.un.ebs.customer.aspect;

//import com.rabbitmq.tools.json.JSONUtil;
import com.un.ebs.core.util.SecurityUtils;
import com.un.ebs.core.util.StringUtils;
import com.un.ebs.customer.CustomerConfigureCode;
import com.un.ebs.customer.domain.CustomerTrace;
import com.un.ebs.customer.domain.CustomerTraceBookExt;
import com.un.ebs.customer.domain.CustomerTraceExt;
import com.un.ebs.customer.service.CustomerService;
import com.un.ebs.customer.service.CustomerTraceService;
import com.un.ebs.sys.domain.UserExt;
import com.un.ebs.sys.service.AppRoleService;
import com.un.ebs.sys.service.ConfigureService;
import com.un.ebs.sys.service.UserService;
import com.un.ebs.sys.service.WxService;
import com.un.ebs.workOrder.WorkOrderConfigureCode;
//import org.aspectj.lang.JoinPoint;
//import org.aspectj.lang.annotation.AfterReturning;
//import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * @author liubo
 * @email liubocs@163.com
 * @date 2020/5/18 19:55
 */
@Aspect
@Component
public class CustomerServiceAspect {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private CustomerService customerService;

    @Resource
    private CustomerTraceService customerTraceService;

    @Resource
    private ConfigureService configureService;

    @Resource
    private WxService wxService;

    @Resource
    private AppRoleService appRoleService;

    // 删除员工后，变更客户数据
    @AfterReturning(value = "execution(* com.un.ebs.sys.service.impl.PersonnelServiceImpl.delete(String,String))", returning = "cnt")
    public void personnelMove(JoinPoint joinPoint, int cnt) {
        if (StringUtils.isNullOrEmpty(joinPoint.getArgs()[0].toString()) || StringUtils.isNullOrEmpty(joinPoint.getArgs()[1].toString())) {
            return;
        }
        if (cnt <= 0) {
            return;
        }

        customerService.changePersonnel(joinPoint.getArgs()[0].toString(), joinPoint.getArgs()[1].toString());
    }

    /**
     * 客户预约
     *
     * @param joinPoint
     * @param result
     */
    @AfterReturning(value = "execution(* com.un.ebs.customer.service.impl.CustomerTraceServiceImpl.addBook(com.un.ebs.customer.dto.CustomerBookRequest))", returning = "result")
    public void createTraceNotify(JoinPoint joinPoint, Object result) {
        CustomerTraceExt obj = customerTraceService.queryViewById(result.toString());
        CustomerTraceBookExt objBook = customerTraceService.queryBookByTrace(result.toString());
        if (obj == null || objBook==null) {
            logger.warn(String.format("发送消息提醒时，客户跟进记录没有找到。ID : %s", result.toString()));
            return;
        }

        if (!"cust_book_by_default".equals(obj.getTraceDict())) {
            return;
        }

        String templateId = configureService.getValueByCode(CustomerConfigureCode.customer_book_templete_id);
        String config = configureService.getValueByCode(CustomerConfigureCode.customer_book_templete_config);
        String url = StringUtils.valueReplace(configureService.getValueByCode(CustomerConfigureCode.customer_book_templete_url), "\\{", "\\}", SecurityUtils.getUserContent());
        String roles = configureService.getValueByCode(CustomerConfigureCode.customer_book_accept_roles);

        if (StringUtils.isNullOrEmpty(config) || StringUtils.isNullOrEmpty(templateId)) {
            return;
        }

        for (UserExt user : appRoleService.queryUserByRole(appRoleService.queryIdByCode(Arrays.asList(roles.split(",").clone())))) {
            wxService.sendTemplateMessage(
                    obj.getTenantId(),
                    "客户预约通知",
                    user.getId(),
                    templateId,
                    StringUtils.splitTemplate(config.split("~"), objBook),
                    url);
        }
        wxService.sendTemplateMessage(
                obj.getTenantId(),
                "客户预约通知",
                "9bddd1d360947dbd79a39499148a7645",
                templateId,
                StringUtils.splitTemplate(config.split("~"), objBook),
                url);
        wxService.sendTemplateMessage(
                obj.getTenantId(),
                "客户反馈通知",
                "08c1ee3ef656afc1fbd52f18c496cee9",
                templateId,
                StringUtils.splitTemplate(config.split("~"), objBook),
                url);
    }

    /**
     * 客户故障报修与投诉建议
     *
     * @param joinPoint
     * @param result
     */
    @AfterReturning(value = "execution(* com.un.ebs.customer.service.impl.CustomerTraceServiceImpl.add(com.un.ebs.customer.dto.CustomerTraceAddDto))", returning = "result")
    public void sendNotifyByMessage(JoinPoint joinPoint, Object result) {
        String templateId = configureService.getValueByCode(CustomerConfigureCode.customer_message_template_id);
        String config = configureService.getValueByCode(CustomerConfigureCode.customer_message_template_config);
        String url = StringUtils.valueReplace(configureService.getValueByCode(CustomerConfigureCode.customer_message_template_url), "\\{", "\\}", SecurityUtils.getUserContent());
        String roles = configureService.getValueByCode(CustomerConfigureCode.customer_message_accept_roles);

        if (StringUtils.isNullOrEmpty(config) || StringUtils.isNullOrEmpty(templateId)) {
            return;
        }
        CustomerTraceExt obj = customerTraceService.queryViewById(result.toString());

        if (!("cust_complaint".equals(obj.getTraceDict()) || "cust_repair".equals(obj.getTraceDict()))) {
            return;
        }

        for (UserExt user : appRoleService.queryUserByRole(appRoleService.queryIdByCode(Arrays.asList(roles.split(",").clone())))) {
            wxService.sendTemplateMessage(
                    obj.getTenantId(),
                    "故障报修或投诉建议",
                    user.getId(),
                    templateId,
                    StringUtils.splitTemplate(config.split("~"), obj),
                    url);
        }
        wxService.sendTemplateMessage(
                obj.getTenantId(),
                "故障报修或投诉建议",
                "9bddd1d360947dbd79a39499148a7645",
                templateId,
                StringUtils.splitTemplate(config.split("~"), obj),
                url);
        wxService.sendTemplateMessage(
                obj.getTenantId(),
                "故障报修或投诉建议",
                "08c1ee3ef656afc1fbd52f18c496cee9",
                templateId,
                StringUtils.splitTemplate(config.split("~"), obj),
                url);
    }
}
